﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Threading;
using System.ComponentModel;

using Microsoft.Practices.Composite;
using Microsoft.Practices.Composite.Presentation.Commands; 

namespace call2sms
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {

        #region commands
        public DelegateCommand<object> CommandServiceStart { get; set; }
        public DelegateCommand<object> CommandServiceStop { get; set; }
        public DelegateCommand<object> CommandServiceConfig { get; set; }
        public DelegateCommand<object> CommandLogExport { get; set; }
        public DelegateCommand<object> CommandLogClear { get; set; }
        public DelegateCommand<object> CommandExit { get; set; }
        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private CallMonitor monitor;
        private SMSSender smsSender;
        private Config config = new Config();

        private string log_text;
        public String LogText
        {
            get { return log_text; }
            set
            {
                log_text = value;
                OnPropertyChanged("LogText");
            }
        }
        public MainWindow()
        {
            CommandServiceStart = new DelegateCommand<object>(DoStartService, CanStartService);
            CommandServiceStop = new DelegateCommand<object>(DoStopService, CanStopService);
            CommandServiceConfig = new DelegateCommand<object>(DoConfigService, CanConfigService);
            CommandLogExport = new DelegateCommand<object>(DoExportLog, CanExportLog);
            CommandLogClear = new DelegateCommand<object>(DoClearLog, CanClearLog);
            CommandExit = new DelegateCommand<object>(DoExit, CanExit);

            InitializeComponent();
            this.DataContext = this;
            LogText = "";
            addLog("Log Start");

           // LogText = "";

        }


        private void onCall(string number)
        {
            this.Dispatcher.Invoke((Action)(()=>{
                addLog(String.Format("呼入号码{0}",number));
                
                bool res = smsSender.SendSMS("呼入电话" + number);
                if(res)
                    addLog(String.Format("发送提示短信成功"));

               
            }));
        }


        private void addLog(string log)
        {
            this.LogText += String.Format("{0}:\t{1}\r\n",System.DateTime.Now,log);
            this.scroller.ScrollToBottom();
        }

        private void onLoaded(object sender, RoutedEventArgs e)
        {
            scroller.ScrollToBottom();
            monitor = new CallMonitor();
            monitor.onCallHandler = onCall;


            LoadConfig();

            if (Properties.Settings.Default.FirstTime)
            {
                Properties.Settings.Default.FirstTime = false;
                DoConfigService(null);
            }
            else
                DoStartService(null);
        }

        private void LoadConfig()
        {
            config.MonitorCom = Properties.Settings.Default.MonitorComm;
            config.SendCom = Properties.Settings.Default.SendComm;
            config.Notify = Properties.Settings.Default.FlagNotify;
            config.Receiver = Properties.Settings.Default.NotifyPhoneNO;
        }

        private void SaveConfig()
        {
            Properties.Settings.Default.MonitorComm = config.MonitorCom;
            Properties.Settings.Default.SendComm = config.SendCom ;
            Properties.Settings.Default.FlagNotify=config.Notify ;
            Properties.Settings.Default.NotifyPhoneNO = config.Receiver ;
            Properties.Settings.Default.Save();
        }
     



        //commands
        bool CanStartService(Object obj)
        {
            return !monitor.IsRunning;
        }

        bool CanStopService(Object obj)
        {
            return monitor.IsRunning;
        }

        bool CanConfigService(Object obj)
        {
            return !monitor.IsRunning;
        }

        bool CanExportLog(Object obj)
        {
            return true;
        }

        bool CanClearLog(Object obj)
        {
            return true;
        }

        bool CanExit(Object obj)
        {
            return true;
        }

        void DoStartService(Object obj)
        {
            try
            {
                monitor.Start(config.MonitorCom);

                if (config.Notify)
                {
                    if(config.MonitorCom == config.SendCom)
                        smsSender = new SMSSender(monitor.Port);
                    else
                        smsSender = new SMSSender(config.SendCom);
                    smsSender.TargetNumber = config.Receiver;
                    smsSender.Init();
                   // smsSender.SendSMS("this is a test fot 放假放假");

                    addLog("发送端口就绪");
                }
                addLog("服务已启动");
            }
            catch (Exception e)
            {
                addLog("出错了"+e.ToString());
                
            }
             
            CommandServiceStart.RaiseCanExecuteChanged();
            CommandServiceStop.RaiseCanExecuteChanged();
            CommandServiceConfig.RaiseCanExecuteChanged();
           
        }

        void DoStopService(Object obj)
        {
            monitor.Stop();
            smsSender = null;
            addLog("服务已停止");
            CommandServiceStart.RaiseCanExecuteChanged();
            CommandServiceStop.RaiseCanExecuteChanged();
            CommandServiceConfig.RaiseCanExecuteChanged();
        }

        void DoConfigService(Object obj)
        {
           

           /* config.MonitorCom = "COM3";
            config.SendCom = "COM3";
            config.Receiver = "13037146556";
            config.Notify = true;*/

            WinConfig dlg = new WinConfig();
            dlg.theConfig = config;

            bool? res = dlg.ShowDialog();
            if (res.HasValue && (bool)res)
            {
                //save setting 

                SaveConfig();
            }
        }


        void DoExportLog(Object obj)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = System.DateTime.Today.ToString("yyyy-MM-dd");
            dlg.DefaultExt = ".log";
           // dlg.Multiselect = true;
            dlg.Filter = @"Log File|*.log";

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                System.IO.StreamWriter writer = System.IO.File.CreateText(filename);
                writer.Write(LogText);
                writer.Close();
            }
        }


        void DoClearLog(Object obj)
        {
            if (MessageBox.Show("清空前需要导出记录吗？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                DoExportLog(null);
            }
            LogText = "";
            scroller.ScrollToHome();

        }


        void DoExit(Object obj)
        {
            
         
            this.Close();
        }

        private void onClosing(object sender, CancelEventArgs e)
        {
            if (MessageBox.Show("退出前需要导出记录吗？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                DoExportLog(null);
            }
            DoStopService(null);
        }

    }
}

